// import mx from 'mxgraph'
// import store from '@/store'
import request from './utils/request'
import mxgraph from './graph/VueMxGraphLoader'

let currentTargetInfo = {};
export function setCurrentTargetInfo(targetInfo) {
	currentTargetInfo = targetInfo;
}
// const mxgraph = mx({
// 	mxBasePath: '/mxgraph',
// 	mxImageBasePath: '/mxgraph/images'
// })

let targetNameList = {};
export function setTargetNameList(list) {
	targetNameList = list;
}

export const {
	mxUtils, //工具类
	mxCell, //组件单位
	mxGraphModel,//画布数据模型,由mxCell数组和其他属性组成
	mxGraph, // 画布对象,主要用作初始化画布
	mxEvent, //事件,宏观的整体的
	mxEventObject, // 事件对象,与mxEvent是所属关系
	mxCodec, // 序列化反序列化
	mxConstants,
	//....
} = mxgraph

export function drawMyOwnGraph(divDom){
	//在divDom这个dom元素上初始化一个画布并返回
	let firstGraph = new mxGraph(divDom)
	// 然后按照文档中修改属性,修改行为,修改事件
	firstGraph.setPanning(false)
	mxEvent.disableContextMenu(divDom)
	firstGraph.setConnectable(true);
	firstGraph.setTooltips(true);
	firstGraph.setAllowDanglingEdges(false);
	firstGraph.setMultigraph(false);
	firstGraph.setCellsEditable(false);

	// var portStyle = new Object()
	// portStyle[mxConstants.STYLE_SHAPE] = mxConstants.SHAPE_IMAGE
	// firstGraph.getStylesheet().putCellStyle('port', portStyle)
	// 锚点 input样式
	// var portInputStyle = new Object() // mxUtils.clone(style);
	// portInputStyle[mxConstants.STYLE_IMAGE] = `${window.SITE_CONFIG.cdnUrl}/static/studio/images/dot.png`
	// firstGraph.getStylesheet().putCellStyle('port-input', portInputStyle)
	// // // 锚点 output样式
	// var portOutputStyle = new Object() // mxUtils.clone(style);
	// portOutputStyle[mxConstants.STYLE_IMAGE] = `${global.PLUGIN_OUTPUT_IMAGE}`
	// firstGraph.getStylesheet().putCellStyle('port-output', portOutputStyle)

	return firstGraph
}

export function makeDraggable(element, graphF, funct, dragElement, dx, dy, autoscroll,
	scalePreview, highlightDropTargets, getDropTarget){
	//最好不用arguments,防止出错
	//拖拽之前,可以添加自己的逻辑
	mxUtils.makeDraggable(element, graphF, funct, dragElement, dx, dy, autoscroll,scalePreview, highlightDropTargets, getDropTarget)
}

export function dragElTree(containerGraph, toolItem, data, saveName) {
	// let {width, height} = data;
	// width = width ? width : 10
	// height = height ? height : 10

	// 拖拽处理函数
	const dropHandler = (graph, evt, cell, x, y)=> {
		//在这里写你的graph.insertVertex函数调用,你可以把你的data放进mxCell的某个域中
		//这段代码应该是流传最多的

		// const realX = drop ? x - dropCell.geometry.x : x;
		// const realY = drop ? y - dropCell.geometry.y : y;
		// const { width, height } = toolItem;
		// const styleObj = toolItem.style;
		// const style = Object.keys(styleObj).map((attr) => `${attr}=${styleObj[attr]}`).join(';');
		// const parent = drop ? dropCell : this.graph.getDefaultParent();
		// graph.getModel().beginUpdate();

		// let parent = graph.getDefaultParent()
		// graph.getModel().beginUpdate();
		// try {
		// 	//这是HelloWorld中的demo
		// 	graph.insertVertex(parent,'123','Hello',20,20,80,30)
		// 	//你既然获取到了你el-tree树节点的data,那你可以在这里使用,假入你的data中有id和name
		// 	// graph.insertVertex(parent,data.id,data.name,横坐标,纵坐标,宽,高)
		// 	//所以你甚至可以提前把宽高这些数据写进数据库,读到树中,然后拖拽到画布中
		// } catch(err) {
		// 	console.log(err)
		// } finally {
		// 	graph.getModel().endUpdate();
		// }
	};

	let generalDropHandler = (graph, evt, dropCell, x, y) => {
		const drop = dropCell;
		// drop && this.$message.info(`${toolItem['title']}节点进入${dropCell.title}`);
		const realX = drop ? x - dropCell.geometry.x : x;
		const realY = drop ? y - dropCell.geometry.y : y;
		// const { width, height } = toolItem;
		let width = 140;
		let height = 40;
		const styleObj = toolItem.style;
		const style = Object.keys(styleObj).map((attr) => `${attr}=${styleObj[attr]}`).join(';');
		// const parent = drop ? dropCell : graph.getDefaultParent();
		// console.log(graph.getModel().getCell('1'))
		// const parent = graph.getModel().getCell('0');
		const parent = data.value == 'FlinkSQL' ? graph.getDefaultParent() : graph.getModel().getCell('1');

		let nameList = targetNameList[data.value];
		let num = 1;
		let newName = '';
		do {
			newName = `${data.value}-${num}`;
			num ++;
		} while(nameList.includes(newName))
		console.log('newName', newName);

		// let lastName = nameList[nameList.length -1];
		// let jobName;
		// if(lastName) {
		// 	let splitArr = lastName.split('-');
		// 	let num = parseInt(splitArr[splitArr.length -1]) + 1;
		// 	jobName = splitArr[0] + '-' + num;
		// } else {
		// 	jobName = data.value + '-' + 1;
		// }
		saveName(data.value, newName);
		// targetNameList[data.value].push(newName);

		request({
			url: '/flink/taskInfo/addAndUpdate',
			method: 'post',
			data: {
				taskType: data.value,
				dirId: currentTargetInfo.id,
			}
		}).then(res=> {
			graph.getModel().beginUpdate();
			try {
				// let vertex = graph.insertVertex(parent, null, null, realX - (width / 2), realY - (height / 2), width, height, style + ';whiteSpace=wrap;word-break=break-all');
				// vertex.title = `<div style='word-break:break-all'>` + toolItem['title'] + '</div>';
				// vertex.dropAble = toolItem['dropAble'];
				// vertex.id = toolItem['id'] + '-' + toolItem['idSeed'];
				// toolItem['idSeed']++;
				// vertex['isGroup'] = toolItem['id'].includes('group') ? true : false

				let vertex = graph.insertVertex(parent, res.id, newName ,realX , realY , width, height, 'fillColor=#3c9afb;strokeColor=white;fontStyle=1;fontColor=white;rounded=1;fontSize=14;');
				// graph.insertVertex(parent, null, newName ,realX , realY , width, height, 'fillColor=#3c9afb;strokeColor=white;fontStyle=1;fontColor=white;rounded=1;fontSize=14;');
				console.log('vertex', vertex);
			} catch(err) {
				console.log('generalDropHandler', err);
			} finally {
				graph.getModel().endUpdate();
			}
		});
	};

	// 拖拽预览形状
	// justify-content: center;
	const dragPreview = () => {
		let cloneNode = toolItem.cloneNode(true);
		cloneNode.style.width = '140px'
		cloneNode.style.height = '40px'
		cloneNode.style.backgroundColor = '#3c9afb';
		cloneNode.style.borderRadius = '8px';
		cloneNode.style.display = 'flex';
		cloneNode.style.justifyContent = 'center';
		cloneNode.style.alignItems = 'center';
		cloneNode.style.color = 'white';
		//你可以使用createDocument新建一个预览DOM然后返回
		return cloneNode;
	}
	// let graph = store.state.app.graph; //这个是我提前放在vuex中的mxGraph对象
	console.log('graph', containerGraph)
	// 可拖动化
	makeDraggable(toolItem, containerGraph, generalDropHandler, dragPreview(), null, null, false, true, true)
}

